package cn.hy.dataSync.config;

import cn.hy.dataSync.constant.Delimiter;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;


@Data
public class WriterConfig implements Serializable {
    private static final long serialVersionUID = -7684648055107027880L;

    private static final int DEFAULT_BATCH_SIZE = 2048;

    /**
     * db 用户名
     */
    private String username;

    /**
     * db 密码
     */
    private String password;

    /**
     * db url
     */
    private String jdbcUrl;

    /**
     * 目标表
     */
    private String table;

    /**
     * 主键
     */
    private String pkName;

    /**
     * 批量提交大小
     */
    private Integer batchSize = DEFAULT_BATCH_SIZE;

    /**
     * 写入模式
     */
    private WriteMode writeMode = WriteMode.INSERT;

    /**
     * 列转换器
     */
    private List<Transformer> transformers;

    /**
     * 将列转换器表达式合并成一个大的表达式，统一计算
     */
    public String generateCombinedExpression() {
        if (CollectionUtils.isEmpty(transformers)) {
            return null;
        }
        StringBuilder expressionBuilder = new StringBuilder();
        for (Transformer transformer : transformers) {
            if (transformer.isDirectMapping()) {
                continue;
            }
            expressionBuilder.append(transformer.getColumn());
            expressionBuilder.append(Delimiter.EQUAL_SIGN);
            expressionBuilder.append(transformer.getExpression());
            expressionBuilder.append(Delimiter.SEMICOLON);
        }
        return expressionBuilder.toString();
    }

    @JSONField(serialize = false)
    public List<String> getColumns() {
        return transformers.stream().map(Transformer::getColumn)
                .collect(Collectors.toList());
    }

    public enum WriteMode {
        //写入模式
        INSERT,
        UPDATE
    }
}
